<template>
	<view class="loginWrap">
		<van-loading size="24px" vertical class="loading" type="spinner" v-if="showLoading">加载中...</van-loading>
		<view v-else>
			<!-- 手机验证码登录 -->
			<view v-if="!isSendcode" class="loginWrapA">
				<view class="loginTitle">
					欢迎登录
				</view>
				<view class="loginForm">
					<view class="uni-input">
						+86<input placeholder="请输入手机号" v-model="phone" maxlength="11" type="number" clearable />
						<text class="icon_close" @click="deletePhone"></text>
					</view>
				</view>

				<view class="loginBtn">
					<button type="primary" style="background-color: #1D78F7;;" :disabled="phone.length == 11 ? false : true" @click="getCode">获取短信验证码</button>
				</view>

				<view>
					<button @click="fillInfo()">跳过</button>
				</view>
			</view>
			<view v-else class="loginWrapB">
				<view class="loginTitle loginTitleB">
					输入验证码
				</view>
				<text class="text-tip">验证码已发送至</text>
				<view style="display: flex;justify-content: space-between;">
					<view style="padding-top: 10rpx;">{{ phone.substring(0,3)+"****"+ phone.substring(7) }}</view>
					<view class="verification-seconds" style="padding-top: 10rpx;">
						<text v-if="seconds*1 !== 0">{{seconds}}秒后重新获取</text>
						<text v-else class="get-code" @click="getCode">重新获取</text>
					</view>
				</view>
				<view class="verification-code">
					<xt-verify-code v-model="verifyCode" @confirm="confirm" type="bottom" :size="4" :isFocus="false" boxNormalColor="#8F92A0" boxActiveColor="#1D78F7" cursorColor="#8F92A0"></xt-verify-code>
				</view>
				<view style="color: #1D78F7; margin-top: 40rpx;" @click="showDialog">收不到验证码?试试语音验证码</view>
			</view>
			<view class="foot">
				<view class="inline left" style="height: 50rpx;width:36rpx;margin-top:7rpx;" @click="bindAcceptRule">
					<image src="@/static/mine/unselected.png" style="width:36rpx;height:36rpx" v-if="!acceptRule">
					</image>
					<image src="@/static/mine/pass.png" style="width:36rpx;height:36rpx" v-if="acceptRule"></image>
				</view>
				<view class="inline left" style="margin-left: 16rpx;color:#9B9B9B;height: 50rpx;line-height: 50rpx;font-size:24rpx;">已阅读并同意
				</view>
				<view class="inline left" style="color:#1D78F7;height: 50rpx;line-height: 50rpx;font-size:24rpx;" @click="goToPolicy('0')">《服务协议》</view>
				<view class="inline left" style="color:#9B9B9B;height: 50rpx;line-height: 50rpx;font-size:24rpx;">与
				</view>
				<view class="inline left" style="color:#1D78F7;height: 50rpx;line-height: 50rpx;font-size:24rpx;" @click="goToPolicy('1')">《隐私政策》</view>
			</view>
		</view>
		<!-- 确认信息是否正确 -->
		<uni-popup ref="popupInfo" type="center" :is-mask-click="false">
			<view class="popup-box2">
				<view class="info-box">
					您将收到语音播报验证码
				</view>
				<view class="btn">
					<button class="btn-box btn-box-left" type="primary" @click="cancel()">暂不方便</button>
					<button class="btn-box btn-box-right" type="primary" @click="call()">免费接听</button>
				</view>
			</view>
		</uni-popup>
	</view>

</template>

<script>
	import {
		getCode,
		Login,
		getSendCallCode,
		getOpenId,
		queryUserByCode
	} from '@/api/login.js'
	import util from '@/utils/util.js';
	export default {
		data() {
			return {
				showLoading: true,
				loginText: '欢迎登录',
				// phone:'',
				isSendcode: false, // 是否发送验证码
				verifyCode: '',
				seconds: 60,
				/* 微信一键登录 */
				phone: '',
				provider: '',
				acceptRule: false,
				pageHeight: '240',
				pageWidth: '320',
				isInputOver: false, //短信验证码自动输入会调用两次，
				openIdCode: '',
				openId: ''
			}
		},
		async onLoad(option) {
			const openId = await util.getOpenId();
			const state = await util.getSignState();
			console.log('openId->',openId,' login state->',state)
			if (!openId) {
				wx.login({
					success: (res) => {
						console.log('微信授权登录', res);
						if (res.code) {
							console.log(res);
							this.openIdCode = res.code;
							this.getUserByWXCode();
						} else {
							this.openIdCode = ''
							console.log('登录失败！' + res.errMsg)
						}
					}
				})
			} else if (state == 'login') {
				uni.switchTab({
					url: '/pages/lock/index'
				})
			} else {
				this.showLoading = false;
			}
		},
		onShow: function() {
			this.pageHeight = this.$sysInfo.windowHeight * 0.8
			this.pageWidth = this.$sysInfo.windowWidth
		},
		methods: {
			bindAcceptRule() {
				// 同意规则
				this.acceptRule = !this.acceptRule;
			},
			goToPolicy(type = '1') {
				if (type === '1') {
					uni.navigateTo({
						url: '/pages/main/login/privacyagreement'
					})
				} else {
					uni.navigateTo({
						url: '/pages/main/login/serviceagreement'
					})
				}
			},
			async getUserByWXCode() {
				const params = {
					'openIdCode': this.openIdCode,
				}
				try {
					const res = await getOpenId(params);
					this.showLoading = false;
					if (res && res.statecode == '0' && res.data) {
						this.openId = res.data.openId
						uni.setStorageSync('openId', this.openId);
						if (res.data.userDto) {
							res.data.userDto.openId = this.openId;
							util.setUserInfo(res.data) // 存全局变量
							uni.setStorage('signInState', 'login') // 设置登录状态
							uni.switchTab({
								url: '/pages/lock/index'
							})
						}
						this.showLoading = false;
					} else {
						util.toast(res.statemsg);
					}
				} catch (err) {
					this.showLoading = false;
					console.log("err:", err)
				}
			},
			async queryUserInfoByWXCode() {
				const params = {
					code: this.openIdCode,
					mobile: '',
				}
				try {
					const res = await queryUserByCode(params);
				} catch (e) {

				}
			},
			//填写信息
			fillInfo() {
				uni.switchTab({
					url: '/pages/lock/index'
				})
			},
			cancel() {
				this.$refs.popupInfo.close()
			},
			call() {
				this.$refs.popupInfo.close()
				this.getVoiceCode()
			},
			showDialog() {
				this.$refs.popupInfo.open()
			},
			/* 
			
				手机验证码模块
			*/
			// 删除手机号码
			deletePhone() {
				this.phone = ''
			},
			//登录提交
			async formSubmit(code) {
				console.log("页面跳转")
				util.loading("正在登录")
				let params = {
					"code": code,
					"mobile": this.phone,
					"openId": this.openId
				}
				const res = await Login(params);
				if (res && res.statecode == 0 && res.data.userDto) {
					uni.hideLoading();
					console.log(res, '获取的数据');
					util.setUserInfo(res.data) // 存全局变量			
					uni.setStorageSync('openId', this.openId);
					uni.setStorageSync('signInState', 'login') // 设置登录状态
					uni.switchTab({
						url: '/pages/lock/index'
					})
				} else {
					uni.hideLoading();
					util.toast(res.statemsg);
				}
			},

			// 获取语音验证码
			async getVoiceCode() {
				if (!this.acceptRule) {
					util.toast("请勾选是否同意协议！")
					return;
				}
				this.isInputOver = false
				let params = {
					"mobile": this.phone,
					"os": this.$userInfo.roleType, //1:房东，2：房客
				}
				util.loading("正在获取语音验证码");
				const res = await getSendCallCode(params);
				uni.hideLoading();
				if (res.statecode == "0") {
					util.toast("语音验证码发送成功，请注意接听电话")
					this.isSendcode = true
				} else {
					util.toast(res.statemsg)
				}
				console.log(res)
			},
			// 获取验证码
			async getCode() {
				if (!this.acceptRule) {
					util.toast("请勾选是否同意协议！")
					return;
				}
				this.isInputOver = false
				let params = {
					"mobile": this.phone,
					"os": this.$userInfo.roleType,
				}
				util.loading("正在获取验证码")
				const res = await getCode(params);
				uni.hideLoading();
				if (res.statecode * 1 === 0) {
					util.toast("验证码已发送")
					this.isSendcode = true
					// 通知验证码组件内部开始倒计时
					this.countDownTime();
				} else {
					util.toast(res.statemsg)
					if ("920010" == res.statecode) {
						this.isSendcode = true
						this.seconds = 0
					}
				}
				console.log(res)
			},
			// 30秒倒计时
			countDownTime() {
				let that = this;
				that.seconds = 60;
				if (that.seconds == 60) {
					let sid = setInterval(function() {
						that.seconds--;
						if (that.seconds == 0) {
							clearInterval(sid);
							that.isInputOver = false
						}
					}, 1000);
				}
			},
			// 验证码输入完毕回调
			confirm(code) {
				console.log('验证码输入完毕', code)
				console.log("Timeout--- 1 ", this.isInputOver)
				if (this.isInputOver) return
				this.isInputOver = true
				var that = this;
				setTimeout(function() { //一秒内只能调用一次
					that.isInputOver = false
					console.log("Timeout---", that.isInputOver)
				}, 1000);
				this.formSubmit(code) // 自动登录
			},

		}
	}
</script>
<style lang="scss" scoped>
	.loginWrap {
		width: 100%;
		padding: 64rpx;
		position: relative;

		.loading {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
		}

		.loginTitle {
			margin: 116rpx 0;
			font-size: 48rpx;
			font-weight: bold;
		}

		.loginForm {
			border-bottom: 2rpx solid #8F92A0;
			padding-bottom: 20rpx;

			.uni-input {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				font-size: 35rpx;

				input {
					height: 60rpx;
					line-height: 60rpx;
					width: 75%;
				}

				.icon_close {
					background: url(../../static/icon/close.png) no-repeat;
					background-size: 100%;
					height: 32rpx;
					width: 32rpx;
				}
			}
		}

		.loginBtn {
			margin: 112rpx 0 48rpx;
		}

		.changeLoginWay {
			text-align: center;
			font-size: 28rpx;
			color: #1F2642;
		}

		.loginWrapB {
			.loginTitleB {
				margin-bottom: 32rpx;
			}

			.text-tip {
				font-size: 28rpx;
				color: #4C5168;
			}

			.verification-seconds {
				flex-direction: row;
				color: #8F92A0;
				font-size: 28rpx;
				margin: 0 0;

				.get-code {
					color: #1D78F7;
				}
			}
		}

		.popup-box2 {
			z-index: 999;
			background: #fff;
			width: 40vh;
			border-radius: 20rpx;
			padding: 60rpx 50rpx 60rpx 50rpx;
			text-align: center;
			color: #1F2642;
			font-size: 32rpx;

			.info-box {
				font-size: 28rpx;
				color: #858B9C;
				margin-top: 10rpx;
				text-align: center;
				padding: 40rpx 40rpx;

				.certNo-box {
					margin-top: 10rpx;
				}
			}

			.btn {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				margin-top: 20rpx;

				.btn-box {
					width: 48%;
					border-radius: 10rpx;
				}

				.btn-box-left {
					background: #fff;
					border: 2rpx solid #4593FF;
					color: #4593FF;
				}

				.btn-box-right {
					background: #4593FF;
					border: 2rpx solid #4593FF;
				}
			}
		}

		.foot {
			position: fixed;
			bottom: 40px;
			width: 82%;
			display: flex;
			justify-content: center;
		}
	}
</style>